import 'package:flutter/material.dart';
import '../models/db_helper.dart';
import 'dart:convert';
import 'package:file_picker/file_picker.dart';
import 'dart:io';
import 'package:sqflite/sqflite.dart';

class PrescriptionPage extends StatefulWidget {
  const PrescriptionPage({Key? key}) : super(key: key);
  @override
  State<PrescriptionPage> createState() => _PrescriptionPageState();
}

class _PrescriptionPageState extends State<PrescriptionPage> {
  List<Map<String, dynamic>> _prescriptions = [];
  List<Map<String, dynamic>> _filtered = [];
  String _search = '';
  Set<String> _selected = {};
  String? _filterJing;
  String? _filterCategory;
  Map<String, int> _jingCount = {};
  Map<String, int> _categoryCount = {};

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  Future<void> _loadData() async {
    final list = await DBHelper.getAllPrescription();
    final jingList = ['太阳经', '阳明经', '少阳经', '太阴经', '少阴经', '厥阴经'];
    Map<String, int> countMap = {for (var j in jingList) j: 0};
    final categoryList = ['解表方', '清热方', '补益方'];
    Map<String, int> catCount = {for (var c in categoryList) c: 0};
    for (var p in list) {
      for (var j in jingList) {
        if ((p['category']?.toString().contains(j) ?? false)) {
          countMap[j] = countMap[j]! + 1;
        }
      }
      for (var c in categoryList) {
        if ((p['category']?.toString().contains(c) ?? false)) {
          catCount[c] = catCount[c]! + 1;
        }
      }
    }
    setState(() {
      _prescriptions = list;
      _filtered = list;
      _jingCount = countMap;
      _categoryCount = catCount;
    });
  }

  void _onSearch(String v) {
    setState(() {
      _search = v;
      _filtered = _prescriptions.where((p) {
        return p['name'].toString().contains(v) ||
               (p['indication']?.toString().contains(v) ?? false) ||
               (p['composition']?.toString().contains(v) ?? false);
      }).toList();
    });
  }

  void _onFilterJing(String? jing) {
    setState(() {
      _filterJing = jing;
      _filtered = _prescriptions.where((p) => jing == null || (p['category']?.toString().contains(jing) ?? false)).toList();
    });
  }

  void _onFilterCategory(String? cat) {
    setState(() {
      _filterCategory = cat;
      _filtered = _prescriptions.where((p) => cat == null || (p['category']?.toString().contains(cat) ?? false)).toList();
    });
  }

  void _showDetail(Map<String, dynamic> p) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: Text(p['name'] ?? ''),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (p['category'] != null) Text('分类：${p['category']}'),
              if (p['composition'] != null) Text('组成：${p['composition']}'),
              if (p['dosage'] != null) Text('剂量：${p['dosage']}'),
              if (p['usage'] != null) Text('用法：${p['usage']}'),
              if (p['indication'] != null) Text('主治：${p['indication']}'),
              if (p['caution'] != null) Text('注意：${p['caution']}'),
              if (p['source'] != null) Text('来源：${p['source']}'),
            ],
          ),
        ),
        actions: [TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('关闭'))],
      ),
    );
  }

  void _onSelect(String id) {
    setState(() {
      if (_selected.contains(id)) {
        _selected.remove(id);
      } else {
        _selected.add(id);
      }
    });
  }

  void _compare() {
    final list = _prescriptions.where((p) => _selected.contains(p['id'])).toList();
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('处方比较'),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: list.map((p) => Padding(
              padding: const EdgeInsets.only(bottom: 12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(p['name'] ?? '', style: const TextStyle(fontWeight: FontWeight.bold)),
                  if (p['composition'] != null) Text('组成：${p['composition']}'),
                  if (p['indication'] != null) Text('主治：${p['indication']}'),
                  if (p['usage'] != null) Text('用法：${p['usage']}'),
                  if (p['caution'] != null) Text('注意：${p['caution']}'),
                ],
              ),
            )).toList(),
          ),
        ),
        actions: [TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('关闭'))],
      ),
    );
  }

  Future<void> _importPrescriptions() async {
    final result = await FilePicker.platform.pickFiles(type: FileType.custom, allowedExtensions: ['json']);
    if (result != null && result.files.single.path != null) {
      final file = result.files.single;
      try {
        final content = await File(file.path!).readAsString();
        final list = json.decode(content);
        if (list is List) {
          for (final p in list) {
            if (p is Map<String, dynamic>) {
              await DBHelper.database.then((db) => db.insert('prescription', p, conflictAlgorithm: ConflictAlgorithm.replace));
            } else if (p is Map) {
              await DBHelper.database.then((db) => db.insert('prescription', Map<String, dynamic>.from(p), conflictAlgorithm: ConflictAlgorithm.replace));
            }
          }
          await _loadData();
          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('处方导入成功')));
        } else {
          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('导入文件格式错误')));
        }
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('导入失败: $e')));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('处方查询'),
        backgroundColor: Colors.brown[50],
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.brown),
          onPressed: () {
            Navigator.of(context).maybePop();
          },
        ),
        actions: [
          if (_selected.isNotEmpty)
            IconButton(
              icon: const Icon(Icons.compare_arrows, color: Colors.brown),
              tooltip: '比较',
              onPressed: _compare,
            ),
          IconButton(
            icon: const Icon(Icons.file_upload, color: Colors.brown),
            tooltip: '导入处方',
            onPressed: _importPrescriptions,
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 搜索栏
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                decoration: BoxDecoration(
                  color: Colors.brown[50],
                  borderRadius: BorderRadius.circular(24),
                ),
                child: Row(
                  children: [
                    const Icon(Icons.search, color: Colors.brown),
                    const SizedBox(width: 8),
                    Expanded(
                      child: TextField(
                        decoration: const InputDecoration(
                          border: InputBorder.none,
                          hintText: '输入方剂名称、功效或组成药材...',
                          hintStyle: TextStyle(color: Colors.brown),
                        ),
                        onChanged: _onSearch,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 16),
              // 六经分类筛选
              const Text('六经分类', style: TextStyle(fontWeight: FontWeight.bold, color: Colors.brown)),
              const SizedBox(height: 12),
              GridView.count(
                crossAxisCount: 3,
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                mainAxisSpacing: 12,
                crossAxisSpacing: 12,
                childAspectRatio: 2.5,
                children: [
                  _JingCard(label: '太阳经', count: _jingCount['太阳经'] ?? 0, icon: Icons.wb_sunny, color: const Color(0xFFD2A06B), onTap: () => _onFilterJing('太阳经')),
                  _JingCard(label: '阳明经', count: _jingCount['阳明经'] ?? 0, icon: Icons.opacity, color: const Color(0xFF80CBC4), onTap: () => _onFilterJing('阳明经')),
                  _JingCard(label: '少阳经', count: _jingCount['少阳经'] ?? 0, icon: Icons.flash_on, color: const Color(0xFFF6D365), onTap: () => _onFilterJing('少阳经')),
                  _JingCard(label: '太阴经', count: _jingCount['太阴经'] ?? 0, icon: Icons.waves, color: const Color(0xFF90CAF9), onTap: () => _onFilterJing('太阴经')),
                  _JingCard(label: '少阴经', count: _jingCount['少阴经'] ?? 0, icon: Icons.nightlight_round, color: const Color(0xFFB39DDB), onTap: () => _onFilterJing('少阴经')),
                  _JingCard(label: '厥阴经', count: _jingCount['厥阴经'] ?? 0, icon: Icons.bubble_chart, color: const Color(0xFF8D6E63), onTap: () => _onFilterJing('厥阴经')),
                ],
              ),
              const SizedBox(height: 24),
              // 处方列表
              const Text('处方列表', style: TextStyle(fontWeight: FontWeight.bold, color: Colors.brown)),
              const SizedBox(height: 12),
              ..._filtered.map((p) => Card(
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                elevation: 1,
                child: ListTile(
                  leading: Checkbox(
                    value: _selected.contains(p['id']),
                    onChanged: (v) => _onSelect(p['id']),
                  ),
                  title: Text(p['name'] ?? '', style: const TextStyle(fontWeight: FontWeight.bold)),
                  subtitle: Text((p['indication'] ?? '') + (p['composition'] != null ? '\n组成：${p['composition']}' : '')),
                  trailing: ElevatedButton(
                    onPressed: () => _showDetail(p),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.brown,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                    ),
                    child: const Text('详情', style: TextStyle(color: Colors.white)),
                  ),
                ),
              )),
              if (_filtered.isEmpty)
                const Padding(
                  padding: EdgeInsets.all(32),
                  child: Center(child: Text('暂无相关处方', style: TextStyle(color: Colors.brown))),
                ),
              const SizedBox(height: 24),
              // 处方分类筛选
              const Text('处方分类', style: TextStyle(fontWeight: FontWeight.bold, color: Colors.brown)),
              const SizedBox(height: 12),
              Row(
                children: [
                  _PrescriptionCategoryCard(label: '解表方', count: _categoryCount['解表方'] ?? 0, icon: Icons.filter_drama, color: Colors.brown, onTap: () => _onFilterCategory('解表方')),
                  const SizedBox(width: 12),
                  _PrescriptionCategoryCard(label: '清热方', count: _categoryCount['清热方'] ?? 0, icon: Icons.opacity, color: Colors.teal, onTap: () => _onFilterCategory('清热方')),
                  const SizedBox(width: 12),
                  _PrescriptionCategoryCard(label: '补益方', count: _categoryCount['补益方'] ?? 0, icon: Icons.bubble_chart, color: Colors.blue, onTap: () => _onFilterCategory('补益方')),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _JingCard extends StatelessWidget {
  final String label;
  final int count;
  final IconData icon;
  final Color color;
  final VoidCallback? onTap;
  const _JingCard({required this.label, required this.count, required this.icon, required this.color, this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Card(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        elevation: 1,
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8),
          child: Row(
            children: [
              Icon(icon, color: color),
              const SizedBox(width: 8),
              Text(label, style: TextStyle(fontWeight: FontWeight.bold, color: color)),
              const Spacer(),
              Text('$count方', style: const TextStyle(color: Colors.brown)),
            ],
          ),
        ),
      ),
    );
  }
}

class _PrescriptionCategoryCard extends StatelessWidget {
  final String label;
  final int count;
  final IconData icon;
  final Color color;
  final VoidCallback? onTap;
  const _PrescriptionCategoryCard({required this.label, required this.count, required this.icon, required this.color, this.onTap});

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: GestureDetector(
        onTap: onTap,
        child: Card(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
          elevation: 1,
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 8),
            child: Row(
              children: [
                Icon(icon, color: color),
                const SizedBox(width: 8),
                Text(label, style: TextStyle(fontWeight: FontWeight.bold, color: color)),
                const Spacer(),
                Text('$count方', style: const TextStyle(color: Colors.brown)),
              ],
            ),
          ),
        ),
      ),
    );
  }
} 